package com.xjz.aop;

import cn.hutool.core.date.StopWatch;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * ClassName: LogInterceptor
 * Package: com.xjz.aop
 * Description:
 *  请求响应日志 AOP
 * @Author 许小健
 * @Create 2025/8/2 15:15
 * @Version 1.0
 */
@Aspect
@Component
@Slf4j
public class LogInterceptor {
    @Around("execution(* com.xjz.controller.*.*(..))")
    public Object doInterceptor(ProceedingJoinPoint point) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        //获取请求路径
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //生成请求唯一Id
        String requestId = UUID.randomUUID().toString();
        String url = request.getRequestURI();
        //获取请求参数
        Object[] args = point.getArgs();
        String reqParam = "[" + StringUtil.join(args,",") + "]";

        //输出请求日志
        log.info("request start,id: {},path: {},ip: {},params: {}",requestId,url,request.getRemoteHost(),reqParam);

        //执行原方法
        Object result = point.proceed();
        //输出响应日志
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        log.info("request end, id : {},cost: {}ms",requestId,totalTimeMillis);
        return result;
    }
}
